package common.convert;

import common.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.Nullable;

/**
 * @title
 * @description
 * @usage
 * @copyright Copyright 2014  rrmj Corporation. All rights reserved.
 * @company 上海众多美网络科技有限公司
 * @author weseal
 * @create 2018/4/19
 */
public final  class EnumConverterFactory implements ConverterFactory<Integer,BaseEnum<?,Integer>> {

	@Override
	public <T extends BaseEnum<?,Integer>> Converter<Integer, T> getConverter(Class<T> targetType) {
		return new EnumConverter(targetType);
	}

	private final static class EnumConverter<T extends BaseEnum<?,Integer>> implements Converter<Integer,T>{

		private Class<T> cls;

		public EnumConverter(Class<T> cls) {
			this.cls = cls;
		}

		@Nullable
		@Override
		public T convert(Integer source) {
			return findEnum(source);
		}

		private T findEnum(Integer source){
			T[] enums = cls.getEnumConstants();
			if (source != null) {
				for (T e : enums) {
					if (e.getCode().equals(source)) {
						return e;
					}
				}
			}
			return null;
		}
	}


}
